package com.catcoin.deposit.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.catcoin.deposit.mapper.RealnameMapper;
import com.catcoin.deposit.model.Realname;
import com.catcoin.deposit.model.User;
import com.catcoin.deposit.model.UsersBankcards;
import com.catcoin.deposit.result.AppResult;
import com.catcoin.deposit.service.IRealnameService;
import com.catcoin.deposit.service.IUserService;
import com.catcoin.deposit.service.IUsersBankcardsService;
import com.catcoin.deposit.util.BankUtils;
import com.catcoin.deposit.util.IpAddressUtils;
import com.catcoin.deposit.util.MSGUtil;
import com.catcoin.deposit.util.StringUtils;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 实名认证信息表 服务实现类
 * </p>
 *
 * @author 1111
 * @since 2018-09-10
 */
@Service
public class RealnameServiceImpl extends ServiceImpl<RealnameMapper, Realname> implements IRealnameService {

    @Autowired
    private RealnameMapper realnameMapper;
    @Autowired
    private IUsersBankcardsService iUsersBankcardsService;
    @Autowired
    private IUserService iUserService;

    @Override
    public Realname selectUsersRealNameByUserId(Integer userId) {
        return realnameMapper.selectUsersRealNameByUserId(userId);
    }

    @Override
    public Realname selectUsersRealNameByCardId(String id) {
        return realnameMapper.selectUsersRealNameByCardId(id);
    }

    @Override
    @Transactional
    public AppResult addRealname(String userPhone, String accUser, String ID, Integer userId, String accNo, HttpServletRequest request) {
        if (MSGUtil.isEmpty(userPhone) || MSGUtil.isEmpty(accUser) || MSGUtil.isEmpty(ID) || MSGUtil.isEmpty(accNo)) {
            return AppResult.ERROR("参数不能为空", -1);
        }
        //查出有没有认证
        Realname usersRealname = realnameMapper.selectUsersRealNameByUserId(userId);
        Integer iRealStatus = getStatusRealName(usersRealname);
        if (!MSGUtil.isBlank(usersRealname) && usersRealname.getAuditStatus() == 1) {
            return AppResult.OK("用户已认证！", 1);
        }
        String errorInfo = "";
        boolean isFlag = true;
        if (userPhone.length() >= 11 && isFlag) {
            if (!StringUtils.checkTel(userPhone)) {
                errorInfo = "请填写正确的联系号码";
                isFlag = false;
            }
        }
        //校验身份证填写
        if (!MSGUtil.verify(ID) && isFlag) {
            errorInfo = "身份证填写不正确";
            isFlag = false;
        }
        //简单校验银行卡
        if (!MSGUtil.checkBankCard(accNo) && isFlag) {
            errorInfo = "卡号输入错误！";
            isFlag = false;
        }
        //校验身份证号码是否已注册
        Realname usersRealname1 = realnameMapper.selectUsersRealNameByCardId(ID);
        if (!MSGUtil.isBlank(usersRealname1) && isFlag) {
            errorInfo = "身份证号码重复，系统已有该号码的用户";
            isFlag = false;
        }
        //过滤填写名字中的特殊字符
        accUser = MSGUtil.StringFilter(accUser);
        if (accUser.equals("") && isFlag) {
            errorInfo = "请填写正确姓名";
            isFlag = false;
        }

        if(!isFlag){
            //有没有记录 有更新2 没有新增0
            if(iRealStatus ==0){
                Integer iReamle = insertReamle(userPhone,accUser,ID,userId,accNo,errorInfo,2,request);
                if(iReamle.intValue()==-1){
                    return AppResult.ERROR("实名表添加失败", -1);
                }
                return AppResult.ERROR(errorInfo, -1);
            }else if(iRealStatus==2){
                usersRealname.setAuditRemark("请填写正确的联系号码");
                usersRealname.setAuditStatus(2);
                Integer iUpdate = updateReamle(usersRealname);
                if(iUpdate.intValue()==-1){
                    return AppResult.ERROR("实名表更新失败", -1);
                }
                return AppResult.ERROR(errorInfo, -1);
            }
        }

        String remark = "";
        //银行卡三要素验证
        JSONObject bankInfoTo3 = BankUtils.getBankInfoTo3(accNo, ID, accUser);
        String status = bankInfoTo3.get("status").toString();
        remark = bankInfoTo3.get("area")!=null?bankInfoTo3.get("area").toString():"";
        if (!status.equals("01")) {

            remark = bankInfoTo3.get("msg").toString();
            if(iRealStatus==2){
                usersRealname.setUserId(userId);
                usersRealname.setCardID(ID);
                usersRealname.setTrueName(accUser);
                usersRealname.setPhone(userPhone);
                usersRealname.setAuditStatus(2);
                usersRealname.setCardAddress(remark);
                Integer integer = realnameMapper.updateById(usersRealname);
                if (integer.intValue() == -1){
                    return AppResult.ERROR("认证表更新失败", -1);
                }
            }else if(iRealStatus==0){
                Integer iReamle = insertReamle(userPhone,accUser,ID,userId,accNo,remark,2,request);
                if(iReamle.intValue()==-1){
                    return AppResult.ERROR("认证表添加失败", -1);
                }
            }

            return AppResult.ERROR("银行卡信息有误,请填写正确信息", -1);


        }else{
            if(iRealStatus==2){
                usersRealname.setUserId(userId);
                usersRealname.setCardID(ID);
                usersRealname.setTrueName(accUser);
                usersRealname.setPhone(userPhone);
                usersRealname.setAuditStatus(1);
                Integer integer = realnameMapper.updateById(usersRealname);
                if (integer.intValue() == 0){
                    return AppResult.ERROR("认证表更新失败", -1);
                }
            }else{
                Integer iReamle = insertReamle(userPhone,accUser,ID,userId,accNo,remark,1,request);
                if(iReamle.intValue()==-1){
                    return AppResult.ERROR("认证表新增失败", -1);
                }
            }

            String accArea = (bankInfoTo3.get("bank")!=null?bankInfoTo3.get("bank").toString():"");
            //-----------------------------------------------------------------------------------------
            UsersBankcards usersBankcards = new UsersBankcards();
            usersBankcards.setUserId(userId);//用户ID
            usersBankcards.setPhone(userPhone);//签约卡的手机号
            usersBankcards.setType(1);//银行卡类型 0充值 支付 1赎回卡
            usersBankcards.setProvinceId(0);//省id
            usersBankcards.setAreaId(0);//区县id
            usersBankcards.setCityId(0);//市id
            usersBankcards.setBankId(0);//银行ID(即开户支行ID)
            usersBankcards.setAccArea(accArea);//开户行
            usersBankcards.setAccNo(accNo);//银行卡号
            usersBankcards.setDataFlag(1);//有效标志
            usersBankcards.setCreateTime(new Date());

            //查询用户银行表
            EntityWrapper<UsersBankcards> ew = new EntityWrapper<UsersBankcards>();
            ew.where("userId = {0}",userId);
            List<UsersBankcards> list = iUsersBankcardsService.selectList(ew);
            boolean insert = true;
            if(list.size()>0){
                usersBankcards.setBankCardId(list.get(0).getBankCardId());
                insert = iUsersBankcardsService.updateById(usersBankcards);
            }else{
                insert = iUsersBankcardsService.insert(usersBankcards);
            }


            if (!insert) {
                return AppResult.ERROR("银行卡认证失败", -1);
            }
            User users = new User();
            users = iUserService.selectById(userId);
            users.setTrueName(accUser);
            boolean b = iUserService.updateById(users);
            if (!b) {
                return AppResult.ERROR("修改真实姓名错误", -1);
            }
        }

        return AppResult.OK("认证成功");
    }

    //添加认证信息
    public Integer insertReamle(String userPhone, String accUser, String ID, Integer userId,
                                String accNo,String remark, Integer auditStatus, HttpServletRequest request){
        Realname usersRealnames = new Realname();
        usersRealnames.setUserId(userId);//用户ID
        usersRealnames.setPhone(userPhone);//签约卡的手机号
        usersRealnames.setTrueName(accUser);//姓名
        usersRealnames.setCardType(1);//证件类型 1二代身份证 2香港 3澳门 4台湾 5新加坡
        usersRealnames.setCardID(ID);//身份证号码
        usersRealnames.setAuditStatus(auditStatus);//审核状态 0 申请中 1 审核通过 2 审核不通过
        usersRealnames.setAuditDatetime(new Date());//审核时间
        usersRealnames.setAddDatetime(new Date());//创建时间
        usersRealnames.setOptTerminal(1);
        usersRealnames.setAuditRemark(remark);//备注
        String ipAddr = IpAddressUtils.getIpAddr(request);
        usersRealnames.setOptIP(ipAddr);
        Integer insert1 = realnameMapper.insert(usersRealnames);
        if (insert1.intValue()==0) {
            return -1;
        }

        return 0;
    }

    //更新认证信息
    public Integer updateReamle(Realname realname){
        Integer insert1 = realnameMapper.updateById(realname);
        if (insert1.intValue()==0) {
            return -1;
        }
        return 0;
    }

    //判断该认证状态
    public Integer getStatusRealName(Realname realname){
        Integer result = 0;
        if(MSGUtil.isBlank(realname)){
            result = 0;
        }else if(realname.getAuditStatus() == 0 || realname.getAuditStatus() == 2){
            result = 2;
        }
        return result;
    }

}
